﻿using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class DataFetcherImpl : IDataFetcher
{
    private const string ApiBase = "http://www.0531yun.com";
    private readonly HttpClient _httpClient = new HttpClient();
    public async Task GetTimedData()
    {
        var reponse=await _httpClient.GetAsync("http://www.0531yun.com/sysData/getRealTimeData?_=1743472110153");
        reponse.Headers.Add("cookie", "SESSION=NWU3NDE5MDYtOTYwNy00MjdhLWE4YTEtMGI4Nzc3NTExYTIz");
        reponse.EnsureSuccessStatusCode();

        var responseStr=await reponse.Content.ReadAsStringAsync();
        var result= JObject.Parse(responseStr);
    }
    public async Task<List<Device>> FetchDeviceListAsync(string token)
    {
        _httpClient.DefaultRequestHeaders.Add("authorization", token);
        try
        {
            var response = await _httpClient.GetAsync($"{ApiBase}/api/device/getDeviceList");
            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<List<Device>>(JObject.Parse(content)["data"].ToString());
        }
        catch (Exception ex)
        {
            throw new System.Exception("设备列表获取失败", ex);
        }
    }

    public async Task<List<RealtimeData>> FetchRealtimeDataAsync(string token, IEnumerable<int> deviceAddrs, DateTime? lastFetchTime)
    {
        _httpClient.DefaultRequestHeaders.Add("authorization", token);
        string requestUrl = $"{ApiBase}/api/data/getRealTimeDataByDeviceAddr?deviceAddrs={string.Join(",", deviceAddrs)}";
        if (lastFetchTime.HasValue)
        {
            requestUrl += $"&since={lastFetchTime.Value:yyyy-MM-dd HH:mm:ss}";
        }

        try
        {
            var response = await _httpClient.GetAsync(requestUrl);
            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<List<RealtimeData>>(JObject.Parse(content)["data"].ToString());
        }
        catch (Exception ex)
        {
            throw new System.Exception("实时数据获取失败", ex);
        }
    }
}